package com.ssyx.home.service.Impl;

import com.ssyx.home.feign.ActivityFeignClient;
import com.ssyx.home.feign.ProductFeignClient;
import com.ssyx.home.service.ItemService;
import com.ssyx.vo.product.SkuInfoVo;
import org.springframework.beans.factory.annotation.Autowire;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;


/**
 * ClassName:ItemServiceImpl
 * Description:
 *
 * @Author kay
 * @Create 2024/5/17 18:21
 * @Version 1.0
 */
@Service
public class ItemServiceImpl implements ItemService {

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @Autowired
    private ProductFeignClient productFeignClient;

    @Autowired
    private ActivityFeignClient activityFeignClient;

    //获取sku详情信息
    //通过CompletableFuture,实现多线程并行,多任务组合完成allOf
    @Override
    public Map<String, Object> index(Long skuId, Long userId) {

        Map<String, Object> result = new HashMap<>();

        // 通过skuId 查询sku基本信息
        CompletableFuture<SkuInfoVo> skuInfoCompletableFuture = CompletableFuture.supplyAsync(() -> {
            SkuInfoVo skuInfoVo = productFeignClient.getById(skuId);
            result.put("skuInfoVo", skuInfoVo);
            return skuInfoVo;
        }, threadPoolExecutor);

        //sku对应的促销与优惠券信息
        CompletableFuture<Void> activityCompletableFuture = CompletableFuture.runAsync(() -> {
            //sku对应的促销与优惠券信息
            Map<String, Object> activityAndCouponMap = activityFeignClient.findActivityAndCoupon(skuId, userId);
            result.putAll(activityAndCouponMap);
        },threadPoolExecutor);

        //TODO 如果商品是秒杀商品，获取秒杀信息

        //  任务组合：
        CompletableFuture.allOf(
                skuInfoCompletableFuture,
                activityCompletableFuture
        ).join();

        return result;
    }
}
